﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace Core
{
    public class Reflector : Core.Component
    {
        private readonly Dictionary<Type, ReflectedCls> dict = new();
        private readonly HashSet<Type> missing = new();

        public void Awake()
        {

        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            dict.Clear();

            base.Dispose();
        }

        private readonly List<FieldInfo> tempFields = new();
        public ReflectedCls GetReflectedCls(Type t)
        {
            if (missing.Contains(t))
            {
                return null;
            }

            if (dict.ContainsKey(t))
            {
                return dict[t];
            }

            Type injectType = typeof(InjectAttribute);
            var fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            tempFields.Clear();
            foreach (var f in fields)
            {
                if (!f.IsDefined(injectType, true))
                {
                    continue;
                }
                tempFields.Add(f);
            }

            if (tempFields.Count > 0)
            {
                var cls = new ReflectedCls();
                dict[t] = cls;
                cls.InjectFields = tempFields.ToArray();
                return cls;
            }

            missing.Add(t);
            return null;
        }
    }
}
